﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.Awesome.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class PersonDataAutocompleteController : Controller
    {
        private IRepo<Person> r;

        public PersonDataAutocompleteController(IRepo<Person> r)
        {
            this.r = r;
        }

        public JsonResult Search(string searchText, int maxResults, IEnumerable<int> hobbies, int? country)
        {
            // ppl that are from country and don't have any of the hobbies
            var res = r.GetAll();
            if(country.HasValue) res = res.Where(o => o.Country.Id == country);
            if (hobbies != null) res = res.Where(o => o.Hobbies.Select(h => h.Id).Intersect(hobbies).Count() == 0);

            return Json(res.Take(maxResults).Select(o => new IdTextItem
                                            {
                                                Id = o.Id,
                                                Text =
                                                    o.FirstName + " " + o.LastName + " hobbies: " +
                                                    String.Join(",", o.Hobbies.Select(h => h.Name).ToArray()) + " from " + o.Country.Name 
            }));
        }
    }

    public class PersonAutocompleteController : Controller
    {
        private readonly IRepo<Person> repo;

        public PersonAutocompleteController(IRepo<Person> repo)
        {
            this.repo = repo;
        }

        public JsonResult Search(string searchText, int maxResults, int? parent)
        {
            var source = parent.HasValue ?
                             repo.GetAll().Where(x => x.Show != null && x.Show.Id == parent.Value)
                             : repo.GetAll();

            return Json(source.Where(o =>
                                     (o.FirstName + " " + o.LastName).ToLower().Contains(searchText.ToLower()))
                            .Select(p => new IdTextItem { Text = p.FirstName + " " + p.LastName, Id = p.Id })
                            .Take(maxResults));
        }
    }
}